<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;
class VoiceController extends Controller
{
    protected $baseUri;
    protected $sname;
    protected $spwd;
    protected $scorpid;
    protected $sprdid;
    protected $client;

    /**
     * @param $apiKey
     */
    public function __construct(){

        // $this->baseUri='http://cf.51welink.com';
        // $this->sname='dlhnqy00';
        // $this->spwd='654321edc';
        // $this->sprdid='1012838';
$this->baseUri='http://cf.51welink.com';
        $this->sname='dlhnqykj';
        $this->spwd='bjbj1234';
        $this->sprdid='1012838';

        $this->client=new Client([
                'base_uri'=>$this->baseUri
        ]);
    }

    /**
     * @param $apiKey
     */
    // public function setApiKey($apiKey){
    //     $this->apiKey=$apiKey;
    // }

    protected function send($path,$params=[],$method='get'){
        if(isset($this->sname)){
            $params['sname']=$this->sname;
        }
        if(isset($this->spwd)){
            $params['spwd']=$this->spwd;
        }
        if(isset($this->sprdid)){
            $params['sprdid']=$this->sprdid;
        }
        if(isset($this->scorpid)){
            $params['scorpid']=$this->scorpid;
        }else{
            $params['scorpid']='';
        }

        $url=$this->baseUri.'/'.$path;
        $method=strtolower($method);

        if($method=='get'){
            $response=$this->client->get($path,[
                'query'=>$params
            ]);
        }else{
            $response=$this->client->post($path,[
                'form_params'=>$params
            ]);
        }

        $response=$this->processResponse($response);

        return $response;
    }

    /**
     * @param ResponseInterface $response
     * @return array
     */
    protected function processResponse(ResponseInterface $response){
        $body=$response->getBody();
        //$size=$body->getSize();
        $cnt=$body->getContents();

        // $cntArr=json_decode($cnt,true);
        $statusCode=$response->getStatusCode();
        // return $body;
        $postObj = simplexml_load_string($cnt, 'SimpleXMLElement', LIBXML_NOCDATA);
        $jsonStr = json_encode($postObj);
        $jsonArray = json_decode($jsonStr,true);
        // $MsgState = $postObj->MsgState;
        return $jsonArray;
    }

    public function sendMsg($phone,$cnt,$options=[]){
        // if(is_array($phone)){
        //     $phone=implode(',',$phone);
        // }
        $params=[
            'sdst' => $phone,
            'smsg' => $cnt,
        ];
        if(!empty($options)){
            $params=array_merge($params,$options);
        }
        $response=$this->send('/submitdata/Service.asmx/g_Submit',$params);

        return $response;
    }
}
